package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.Counselor;
import com.example.chamberlainserver.Service.CounselorService;
import com.example.chamberlainserver.dto.CounselorDTO;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 辅导员管理控制器
 */
@RestController
@RequestMapping("/counselors")
@Validated
public class CounselorController {

    @Autowired
    private CounselorService counselorService;

    /**
     * 查询所有辅导员
     */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<List<Counselor>>> getAllCounselors() {
        try {
            List<Counselor> counselors = counselorService.getAllCounselors();
            return ResponseEntity.ok(ApiResponse.success("查询辅导员列表成功", counselors));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询辅导员列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID查询辅导员
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Counselor>> getCounselorById(@PathVariable @NotNull Long id) {
        try {
            Counselor counselor = counselorService.getCounselorById(id);
            if (counselor != null) {
                return ResponseEntity.ok(ApiResponse.success("查询辅导员成功", counselor));
            } else {
                return ResponseEntity.ok(ApiResponse.error("辅导员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 根据工号查询辅导员
     */
    @GetMapping("/employee/{employeeId}")
    public ResponseEntity<ApiResponse<Counselor>> getCounselorByEmployeeId(@PathVariable @NotEmpty String employeeId) {
        try {
            Counselor counselor = counselorService.getCounselorByEmployeeId(employeeId);
            if (counselor != null) {
                return ResponseEntity.ok(ApiResponse.success("查询辅导员成功", counselor));
            } else {
                return ResponseEntity.ok(ApiResponse.error("辅导员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询辅导员
     */
    @GetMapping("/page")
    public ResponseEntity<ApiResponse<PageResult<Counselor>>> getCounselorsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) Integer status) {
        try {
            PageResult<Counselor> result = counselorService.getCounselorsByPage(page, size, name, department, status);
            return ResponseEntity.ok(ApiResponse.success("分页查询辅导员成功", result));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("分页查询辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 创建辅导员
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Counselor>> createCounselor(@RequestBody @Valid CounselorDTO counselorDTO) {
        try {
            // 验证工号唯一性
            if (!counselorService.isEmployeeIdUnique(counselorDTO.getEmployeeId(), null)) {
                return ResponseEntity.ok(ApiResponse.error("工号已存在"));
            }
            
            // 验证邮箱唯一性
            if (counselorDTO.getEmail() != null && !counselorService.isEmailUnique(counselorDTO.getEmail(), null)) {
                return ResponseEntity.ok(ApiResponse.error("邮箱已存在"));
            }
            
            // 验证手机号唯一性
            if (counselorDTO.getPhone() != null && !counselorService.isPhoneUnique(counselorDTO.getPhone(), null)) {
                return ResponseEntity.ok(ApiResponse.error("手机号已存在"));
            }
            
            Counselor counselor = counselorService.createCounselor(counselorDTO);
            return ResponseEntity.ok(ApiResponse.success("创建辅导员成功", counselor));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("创建辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 更新辅导员信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Counselor>> updateCounselor(@PathVariable @NotNull Long id, 
                                           @RequestBody @Valid CounselorDTO counselorDTO) {
        try {
            // 验证辅导员是否存在
            Counselor existingCounselor = counselorService.getCounselorById(id);
            if (existingCounselor == null) {
                return ResponseEntity.ok(ApiResponse.error("辅导员不存在"));
            }
            
            // 验证工号唯一性
            if (!counselorService.isEmployeeIdUnique(counselorDTO.getEmployeeId(), id)) {
                return ResponseEntity.ok(ApiResponse.error("工号已存在"));
            }
            
            // 验证邮箱唯一性
            if (counselorDTO.getEmail() != null && !counselorService.isEmailUnique(counselorDTO.getEmail(), id)) {
                return ResponseEntity.ok(ApiResponse.error("邮箱已存在"));
            }
            
            // 验证手机号唯一性
            if (counselorDTO.getPhone() != null && !counselorService.isPhoneUnique(counselorDTO.getPhone(), id)) {
                return ResponseEntity.ok(ApiResponse.error("手机号已存在"));
            }
            
            Counselor counselor = counselorService.updateCounselor(id, counselorDTO);
            return ResponseEntity.ok(ApiResponse.success("更新辅导员成功", counselor));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 删除辅导员
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteCounselor(@PathVariable @NotNull Long id) {
        try {
            boolean success = counselorService.deleteCounselor(id);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除成功", "删除成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除失败，辅导员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除辅导员
     */
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<String>> deleteCounselors(@RequestBody @NotEmpty List<Long> ids) {
        try {
            int deletedCount = counselorService.deleteCounselors(ids);
            return ResponseEntity.ok(ApiResponse.success("批量删除成功", "成功删除 " + deletedCount + " 个辅导员"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量删除辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 根据班级ID查询辅导员
     */
    @GetMapping("/class/{classId}")
    public ResponseEntity<ApiResponse<List<Counselor>>> getCounselorsByClassId(@PathVariable @NotNull Long classId) {
        try {
            List<Counselor> counselors = counselorService.getCounselorsByClassId(classId);
            return ResponseEntity.ok(ApiResponse.success("查询班级辅导员成功", counselors));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询班级辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 查询未分配班级的辅导员
     */
    @GetMapping("/unassigned")
    public ResponseEntity<ApiResponse<List<Counselor>>> getUnassignedCounselors() {
        try {
            List<Counselor> counselors = counselorService.getUnassignedCounselors();
            return ResponseEntity.ok(ApiResponse.success("查询未分配辅导员成功", counselors));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询未分配辅导员失败: " + e.getMessage()));
        }
    }

    /**
     * 更新辅导员状态
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<String>> updateCounselorStatus(@PathVariable @NotNull Long id, 
                                              @RequestBody Map<String, Integer> statusMap) {
        try {
            Integer status = statusMap.get("status");
            if (status == null) {
                return ResponseEntity.ok(ApiResponse.error("状态参数不能为空"));
            }
            
            boolean success = counselorService.updateCounselorStatus(id, status);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("状态更新成功", "状态更新成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("状态更新失败，辅导员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新辅导员状态失败: " + e.getMessage()));
        }
    }

    /**
     * 更新辅导员权限
     */
    @PatchMapping("/{id}/permissions")
    public ResponseEntity<ApiResponse<String>> updateCounselorPermissions(@PathVariable @NotNull Long id, 
                                                    @RequestBody Map<String, String> permissionsMap) {
        try {
            String permissions = permissionsMap.get("permissions");
            if (permissions == null) {
                return ResponseEntity.ok(ApiResponse.error("权限参数不能为空"));
            }
            
            boolean success = counselorService.updateCounselorPermissions(id, permissions);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("权限更新成功", "权限更新成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("权限更新失败，辅导员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新辅导员权限失败: " + e.getMessage()));
        }
    }
}